<template>
  <div class="login-container">
    <el-card class="login-card" shadow="always">
      <h2 class="login-title">登录</h2>
      <el-form :model="form" ref="formRef" status-icon label-width="80px">
        <el-form-item label="用户名" prop="username" :rules="usernameRules">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" :rules="passwordRules">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="handleLogin">登录</el-button>
    </el-card>
  </div>
</template>
  
  <script setup>
import { ref } from "vue";
import { logins } from "../api/login";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router"; // 引入路由
const router = useRouter(); // 创建路由实例
const formRef = ref(null);
const form = ref({
  username: "",
  password: "",
});

const usernameRules = [
  { required: true, message: "请输入用户名", trigger: "blur" },
];

const passwordRules = [
  { required: true, message: "请输入密码", trigger: "blur" },
];

const handleLogin = async () => {
  try {
    await formRef.value.validate();
    // 在这里执行登录逻辑
    const response = await logins(form.value.username, form.value.password);
    ElMessage({
      message: response.message,
    });
    if (response.status === 200) {
      localStorage.setItem("userData", JSON.stringify(response.data));
      // 跳转到主路由
      router.push("/");
    }
  } catch (error) {
    console.error("登录验证失败", error);
  }
};
</script>
  
  <style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #409eff; /* Element Plus 默认蓝色 */
}

.el-form-item {
  margin-bottom: 20px; /* 可选：调整输入框之间的间距 */
}
:deep(.el-button) {
  width: 100px;
  margin: 0 130px;
}
</style>
  